using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net;
using System.Reflection;
using System.Xml;
using System.IO;
using System.Threading;

namespace DataLoad.iContact.WinClient
{
    public partial class frmCheckForUpdates : Form
    {
        public frmCheckForUpdates()
        {
            InitializeComponent();
        }

        public static void CheckforUpdates()
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                DoCheckforUpdates();
            });
        }

        private static void DoCheckforUpdates()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                using (WebClient client = new WebClient())
                {
                    using (Stream stream = client.OpenRead("http://www.dataload.com/icontact/download/clientVersion.xml"))
                    {
                        doc.Load(stream);
                    }
                }

                string latestVersion = doc["dataLoad"]["iContact"]["latestVersion"].InnerText;
                bool major = bool.Parse(doc["dataLoad"]["iContact"]["major"].InnerText);

                string currentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

                if (latestVersion != currentVersion)
                {
                    using (frmCheckForUpdates frm = new frmCheckForUpdates())
                    {
                        if (frm.InvokeRequired)
                        {
                            frm.Invoke((ThreadStart)delegate
                            {
                                frm.ShowDialog();
                            });
                        }
                        else
                        {
                            frm.ShowDialog();
                        }
                    }
                }
            }
            catch
            {
                // Do nothing
            }
        }

        private void lblLink_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("http://www.dataload.com/icontact");
            }
            catch
            {
                MessageBox.Show("Unable to start the web browser", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}